<?php

/** 
 * 订单_控制器
 * @property Order_cache_mdl $orderCache
 */
class Order extends MY_Controller {
	
	public function __construct() {
		parent::__construct ();
		$this->user = parent::getLoginUser();
		$this->load->model('Order_cache_mdl','orderCache');
		
// 		$this->order->setUserID($this->user->id);
	}
	/**
	 * API:用户订单列表
	 * 输入参数:
	 * 		count:请求多少条
	 * 		bottomID:要获取的订单的最大ID
	 */
	public function index(){
		$bottomID = ( int ) $this->input->post_get ( 'bottomID' );
		$count = ( int ) $this->input->post_get ( 'count' );
		$count = $count > 0 ? $count : 20;
		
		$fields = array (
				'_id'=>false,
				'nickname'=>false,
				'updateTime'=>false,
				'devID'=>false,
				'schoolID'=>false,
		);
		
		$where = array ();
		$tableID = $this->user->id % 10;
		$maxID = $bottomID > 0 ? $bottomID : 99999999;
		$where ['_id'] ['$gte'] = ( int ) sprintf ( "%1d%08d", $tableID, 0 );
		$where ['_id'] ['$lt'] = ( int ) sprintf ( "%1d%08d", $tableID, $maxID );
		$where ['userID'] = ( int ) $this->user->id;
		$where ['isFinish'] = 1;
		$sort = array ('_id' => - 1 );
		$list = $this->orderCache->getOrders ( $fields, $where, $count+1, 0, $sort );
		
		$hasMore = 0;
		$listCount = count($list);
		if ($listCount > $count) {
			$hasMore = 1;
			array_pop ( $list );
			$listCount-=1;
		}
		$bottomID = empty( $list[$listCount-1]['id']) ? 0 : $list[$listCount-1]['id'] ;
		

		
		$list = array_map(function($order){
			$order['beginTime'] = $order['createTime'];
			unset($order['createTime']);
			
			$title = '';
			if($order['type']==BUY_MODE_ONCE){
				$title = '洗衣机模式';
			}elseif($order['type']==BUY_MODE_PULES_HOT||$order['type']==BUY_MODE_PULES_COLD){ 
				$title .= '洗澡用水';
			}else{
				$title .= $order['mode']==1 ? '在线':'离线';
				$title .= '取水'.$order['takeSec'].'秒';
			}
			
			$order['txt'] = $title;
			
			if($order['beginTime']<=0){
				$order['beginTime'] = time();
			}
			if( $order['type'] <=0 ){
				$order['type'] = 1;
			}
			
			return $order;
		}, $list);

		$this->apiOutput->put ( 'hasMore', $hasMore )
						->put('bottomID', (string)$bottomID)
						->put ( 'list', $list )
						->out ();
	}

}

